﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace XCI.Windows
{
    /// <summary>
    /// 选项卡控件动态加载控制(只有第一次激活时才执行代码)
    /// </summary>
    public class TabDelayLoad
    {
        /// <summary>
        /// 已经加载的页面
        /// </summary>
        private readonly Dictionary<string,int> loads = new Dictionary<string, int>(5);
        private Action<string> _loadAction { get; set; }

        /// <summary>
        /// 初始化
        /// </summary>
        public TabDelayLoad(Action<string> loadAction)
        {
            this._loadAction = loadAction;
        }

        public TabDelayLoad(DevExpress.XtraTab.XtraTabControl tabControl, Action<string> loadAction) :this(loadAction)
        {
            Load(tabControl.SelectedTabPage.Name);
            tabControl.SelectedPageChanged += (o, e) =>
            {
                Load(e.Page.Name);
            };
        }

        public TabDelayLoad(DevExpress.XtraBars.Navigation.TabPane tabPane, Action<string> loadAction) : this(loadAction)
        {
            Load(tabPane.SelectedPage.Name);
            tabPane.SelectedPageChanged += (o, e) =>
            {
                Load(((Control)e.Page).Name);
            };
        }

        /// <summary>
        /// 加载Tab页
        /// </summary>
        /// <param name="name">Tab页名称</param>
        public void Load(string name)
        {
            if (loads.ContainsKey(name)) return;

            loads[name] = 1;
            _loadAction?.Invoke(name);
        }

        /// <summary>
        /// 清空加载状态
        /// </summary>
        public void Clear()
        {
            loads.Clear();
        }
    }
}